#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Module Description:工具装饰器
Date: 2016/5/17
Author:Bai Jin Ping
"""
from pyshare.utils.traceback_utils import print_exc
from functools import wraps


def catch_err(func):
    """
    错误捕获

    >>> @catch_err
    >>> def func():
    >>>       pass
    :return:
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print_exc(e)
            pass
    return wrapper


def catch_err_with_dft_rtn(default_rtn=None):
    """
    错误捕获,并可设置报错时的返回值

    >>> @catch_err_with_dft_rtn(default_rtn=3)
    >>> def func():
    >>>       pass

    :param default_rtn:报错时返回的值
    :return
    """
    def out_wrapper(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                print_exc(e)
                return default_rtn
        return wrapper
    return out_wrapper


if __name__ == '__main__':
    class Obj(object):
        @catch_err
        def test_catch_err(self):
            raise StandardError('dd')

        @catch_err_with_dft_rtn(default_rtn=5)
        def test_catch_err_with_rtn(self):
            raise StandardError('dd')

    @catch_err
    def add(x):
        raise StandardError('ddd')

    print add(1)
    print 'after func'

    obj = Obj()
    print obj.test_catch_err()
    print obj.test_catch_err_with_rtn()
    print 'after class func'
